# 音频转文字服务配置

import os
from typing import List, Dict, Optional
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    """
    音频转文字服务配置类
    基于OpenAI Whisper的高性能语音识别服务
    """
    # 项目基本信息
    PROJECT_NAME: str = "音频转文字服务"
    PROJECT_DESCRIPTION: str = "基于OpenAI Whisper的高精度音频转文字API服务"
    VERSION: str = "1.0.0"
    API_PREFIX: str = "/api/v1"
    
    # CORS配置
    CORS_ORIGINS: str = os.getenv("CORS_ORIGINS", "http://localhost:3000")
    
    @property
    def cors_origins_list(self) -> List[str]:
        """将CORS_ORIGINS字符串转换为列表"""
        if isinstance(self.CORS_ORIGINS, str):
            return [origin.strip() for origin in self.CORS_ORIGINS.split(",")]
        return self.CORS_ORIGINS

    # 音频处理配置 - 优化内存使用
    MAX_AUDIO_SIZE_MB: int = int(os.getenv("MAX_AUDIO_SIZE_MB", "50"))   # 最大音频文件大小(MB) - 降低以减少内存压力
    SUPPORTED_AUDIO_FORMATS: List[str] = ["wav", "mp3", "ogg", "flac", "m4a", "aac", "wma"]
    TEMP_UPLOAD_DIR: str = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "uploads")
    OUTPUT_DIR: str = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "output")
    
    # Whisper模型配置 - 优化内存使用
    WHISPER_MODEL: str = os.getenv("WHISPER_MODEL", "base")  # 默认使用base模型以减少内存占用
    WHISPER_DEVICE: str = os.getenv("WHISPER_DEVICE", "auto")  # auto, cpu, cuda
    WHISPER_COMPUTE_TYPE: str = os.getenv("WHISPER_COMPUTE_TYPE", "default")  # default, int8, float16
    
    # Whisper可用模型配置
    AVAILABLE_WHISPER_MODELS: Dict[str, Dict[str, str]] = {
        "tiny": {
            "size": "39M",
            "vram": "~1GB", 
            "speed": "~10x",
            "description": "最快速度，适合实时处理"
        },
        "tiny.en": {
            "size": "39M",
            "vram": "~1GB",
            "speed": "~10x", 
            "description": "英语专用，最快速度"
        },
        "base": {
            "size": "74M",
            "vram": "~1GB",
            "speed": "~7x",
            "description": "平衡速度和精度，推荐默认选择"
        },
        "base.en": {
            "size": "74M",
            "vram": "~1GB",
            "speed": "~7x",
            "description": "英语专用，平衡速度和精度"
        },
        "small": {
            "size": "244M",
            "vram": "~2GB",
            "speed": "~4x",
            "description": "较高精度，适合大多数应用"
        },
        "small.en": {
            "size": "244M",
            "vram": "~2GB",
            "speed": "~4x",
            "description": "英语专用，较高精度"
        },
        "medium": {
            "size": "769M",
            "vram": "~5GB",
            "speed": "~2x",
            "description": "高精度，适合专业应用"
        },
        "medium.en": {
            "size": "769M",
            "vram": "~5GB",
            "speed": "~2x",
            "description": "英语专用，高精度"
        },
        "large": {
            "size": "1550M",
            "vram": "~10GB",
            "speed": "1x",
            "description": "最高精度，适合高质量转录"
        },
        "large-v2": {
            "size": "1550M",
            "vram": "~10GB",
            "speed": "1x",
            "description": "最高精度v2版本"
        },
        "large-v3": {
            "size": "1550M",
            "vram": "~10GB",
            "speed": "1x",
            "description": "最新最高精度版本"
        },
        "turbo": {
            "size": "809M",
            "vram": "~6GB",
            "speed": "~8x",
            "description": "优化版large-v3，速度更快"
        }
    }
    
    # 语言支持配置
    DEFAULT_LANGUAGE: str = os.getenv("DEFAULT_AUDIO_LANGUAGE", "zh-CN")  # 默认识别语言
    SUPPORTED_LANGUAGES: List[str] = [
        "zh-CN", "zh-TW", "en-US", "en-GB", "ja-JP", "ko-KR", 
        "fr-FR", "de-DE", "es-ES", "it-IT", "pt-PT", "pt-BR",
        "ru-RU", "ar-SA", "hi-IN", "th-TH", "vi-VN", "auto"
    ]
    
    # Whisper处理参数
    WHISPER_TEMPERATURE: float = 0.0  # 采样温度，0为确定性输出
    WHISPER_BEST_OF: int = 5  # 候选数量
    WHISPER_BEAM_SIZE: int = 5  # 束搜索大小
    WHISPER_PATIENCE: float = 1.0  # 束搜索耐心值
    WHISPER_LENGTH_PENALTY: float = 1.0  # 长度惩罚
    WHISPER_SUPPRESS_TOKENS: str = "-1"  # 抑制的token
    WHISPER_INITIAL_PROMPT: Optional[str] = None  # 初始提示
    WHISPER_CONDITION_ON_PREVIOUS_TEXT: bool = True  # 基于前文条件化
    WHISPER_FP16: bool = True  # 使用FP16精度
    WHISPER_COMPRESSION_RATIO_THRESHOLD: float = 2.4  # 压缩比阈值
    WHISPER_LOGPROB_THRESHOLD: float = -1.0  # 对数概率阈值
    WHISPER_NO_SPEECH_THRESHOLD: float = 0.6  # 无语音阈值
    
    # 监控配置
    MONITORING_ENABLED: bool = os.getenv("MONITORING_ENABLED", "true").lower() == "true"
    METRICS_RETENTION_HOURS: int = int(os.getenv("METRICS_RETENTION_HOURS", "24"))
    SYSTEM_METRICS_INTERVAL: int = int(os.getenv("SYSTEM_METRICS_INTERVAL", "30"))  # 秒
    MAX_HISTORY_SIZE: int = int(os.getenv("MAX_HISTORY_SIZE", "1000"))
    # 更严格的健康检查阈值以提前预警
    HEALTH_CHECK_CPU_THRESHOLD: float = float(os.getenv("HEALTH_CHECK_CPU_THRESHOLD", "80.0"))  # 降低CPU阈值
    HEALTH_CHECK_MEMORY_THRESHOLD: float = float(os.getenv("HEALTH_CHECK_MEMORY_THRESHOLD", "75.0"))  # 降低内存阈值
    HEALTH_CHECK_ERROR_RATE_THRESHOLD: float = float(os.getenv("HEALTH_CHECK_ERROR_RATE_THRESHOLD", "10.0"))
    METRICS_EXPORT_PATH: str = os.getenv("METRICS_EXPORT_PATH", "./monitoring_data.json")
    
    # 安全配置
    API_KEY_HEADER: str = "X-API-Key"
    API_KEY: str = os.getenv("API_KEY", "")
    
    model_config = {
        "case_sensitive": True,
        "env_file": os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))), ".env"),
        "extra": "ignore"  # 忽略额外的环境变量
    }

# 创建全局设置实例
settings = Settings()

# 确保临时目录存在
os.makedirs(settings.TEMP_UPLOAD_DIR, exist_ok=True)